import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Trash2, Plus, Minus, ShoppingBag, ArrowRight } from 'lucide-react';
import { useAppStore, CartItem } from '../stores/appStore';
import { Header } from '../components/Header';
import { BottomNav } from '../components/BottomNav';

export const CartPage: React.FC = () => {
  const navigate = useNavigate();
  const { currentUser, removeFromCart, updateCartItemQuantity, clearCart, addOrder, showToast } = useAppStore();
  
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [isProcessing, setIsProcessing] = useState(false);

  if (!currentUser) {
    navigate('/login');
    return null;
  }

  const cartItems = currentUser.cart;
  
  const selectedCartItems = cartItems.filter(item => selectedItems.has(item.id));
  const totalAmount = selectedCartItems.reduce((total, item) => total + (item.price * item.quantity), 0);

  const handleSelectItem = (itemId: string) => {
    const newSelected = new Set(selectedItems);
    if (newSelected.has(itemId)) {
      newSelected.delete(itemId);
    } else {
      newSelected.add(itemId);
    }
    setSelectedItems(newSelected);
  };

  const handleSelectAll = () => {
    if (selectedItems.size === cartItems.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(cartItems.map(item => item.id)));
    }
  };

  const handleQuantityChange = (itemId: string, newQuantity: number) => {
    if (newQuantity >= 1) {
      updateCartItemQuantity(itemId, newQuantity);
    }
  };

  const handleRemoveItem = (itemId: string) => {
    removeFromCart(itemId);
    const newSelected = new Set(selectedItems);
    newSelected.delete(itemId);
    setSelectedItems(newSelected);
    showToast('商品已从购物车移除', 'info');
  };

  const handleCheckout = async () => {
    if (selectedCartItems.length === 0) {
      showToast('请选择要购买的商品', 'error');
      return;
    }

    setIsProcessing(true);
    
    // 模拟支付处理
    setTimeout(() => {
      const order = {
        id: `order_${Date.now()}`,
        userId: currentUser.id,
        items: selectedCartItems,
        totalAmount,
        status: 'paid' as const,
        paymentMethod: '微信支付',
        createdAt: new Date().toISOString(),
        paidAt: new Date().toISOString()
      };

      addOrder(order);
      
      // 从购物车中移除已购买的商品
      selectedCartItems.forEach(item => {
        removeFromCart(item.id);
      });
      
      setSelectedItems(new Set());
      setIsProcessing(false);
      showToast('支付成功！订单已创建', 'success');
      navigate('/profile');
    }, 2000);
  };

  if (cartItems.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header title="购物车" />
        
        <div className="pt-16 pb-20">
          <div className="flex flex-col items-center justify-center h-96">
            <ShoppingBag className="w-16 h-16 text-gray-300 mb-4" />
            <h3 className="text-lg font-medium text-gray-600 mb-2">购物车是空的</h3>
            <p className="text-gray-500 mb-6">快去挑选喜欢的绘本和活动吧！</p>
            <button
              onClick={() => navigate('/books')}
              className="bg-primary text-white px-6 py-3 rounded-lg font-medium hover:bg-primary/90 transition-colors"
            >
              去逛逛
            </button>
          </div>
        </div>
        
        <BottomNav />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Header title="购物车" />
      
      <div className="pt-16 pb-32">
        {/* 全选栏 */}
        <div className="bg-white px-4 py-3 border-b border-gray-200">
          <label className="flex items-center">
            <input
              type="checkbox"
              checked={selectedItems.size === cartItems.length && cartItems.length > 0}
              onChange={handleSelectAll}
              className="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary"
            />
            <span className="ml-2 text-sm font-medium">全选</span>
          </label>
        </div>

        {/* 购物车商品 */}
        <div className="space-y-4 p-4">
          {cartItems.map((item) => (
            <div key={item.id} className="bg-white rounded-lg p-4 shadow-sm">
              <div className="flex items-start space-x-3">
                <label className="flex-shrink-0 mt-1">
                  <input
                    type="checkbox"
                    checked={selectedItems.has(item.id)}
                    onChange={() => handleSelectItem(item.id)}
                    className="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary"
                  />
                </label>
                
                <img
                  src={item.image}
                  alt={item.title}
                  className="w-20 h-20 object-cover rounded-lg flex-shrink-0"
                />
                
                <div className="flex-1 min-w-0">
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <h3 className="font-medium text-gray-900 line-clamp-2">
                        {item.title}
                      </h3>
                      <p className="text-sm text-gray-500 mt-1">
                        {item.type === 'book' ? '绘本' : '活动'}
                      </p>
                    </div>
                    <button
                      onClick={() => handleRemoveItem(item.id)}
                      className="text-gray-400 hover:text-red-500 transition-colors p-1"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                  
                  <div className="flex items-center justify-between mt-3">
                    <div className="flex items-center space-x-2">
                      <button
                        onClick={() => handleQuantityChange(item.id, item.quantity - 1)}
                        className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                      >
                        <Minus className="w-4 h-4" />
                      </button>
                      <span className="w-8 text-center font-medium">{item.quantity}</span>
                      <button
                        onClick={() => handleQuantityChange(item.id, item.quantity + 1)}
                        className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-gray-50"
                      >
                        <Plus className="w-4 h-4" />
                      </button>
                    </div>
                    <div className="text-right">
                      <span className="text-lg font-bold text-primary">
                        ¥{(item.price * item.quantity).toFixed(2)}
                      </span>
                      <div className="text-sm text-gray-500">
                        ¥{item.price.toFixed(2)}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 底部结算栏 */}
      <div className="fixed bottom-16 left-0 right-0 bg-white border-t border-gray-200 p-4">
        <div className="flex items-center justify-between mb-4">
          <div className="text-sm text-gray-600">
            已选 <span className="font-medium text-primary">{selectedCartItems.length}</span> 件
          </div>
          <div className="flex items-center space-x-2">
            <span className="text-sm text-gray-600">合计:</span>
            <span className="text-xl font-bold text-primary">¥{totalAmount.toFixed(2)}</span>
          </div>
        </div>
        
        <button
          onClick={handleCheckout}
          disabled={selectedCartItems.length === 0 || isProcessing}
          className="w-full bg-primary text-white py-3 rounded-lg font-medium flex items-center justify-center space-x-2 hover:bg-primary/90 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
        >
          {isProcessing ? (
            <>
              <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
              <span>处理中...</span>
            </>
          ) : (
            <>
              <span>结算</span>
              <ArrowRight className="w-4 h-4" />
            </>
          )}
        </button>
      </div>
      
      <BottomNav />
    </div>
  );
};